package org.tech4j.common.core.sign.provider;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.tech4j.common.core.constant.Constants;
import org.tech4j.common.core.sign.api.SignParameters;
import org.tech4j.common.utils.JsonUtils;
import org.tech4j.common.utils.SignUtils;

import java.util.Comparator;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @program: tech4j-common
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/2 21:14
 **/
public class VersionOneSignProvider implements SignProvider {

    @Override
    public String generateSign(String signKey, SignParameters signParameters) {
        return sign(signKey, signParameters);
    }

    private String sign(final String signKey, final SignParameters signParameters) {
        Map<String, String> params = getParams(signParameters);
        final String data = params.keySet().stream()
                .sorted(Comparator.naturalOrder())
                .filter(key -> !StringUtils.equals(key, Constants.SIGN))
                .map(key -> String.join("", key, params.get(key)))
                .collect(Collectors.joining()).trim();

        return SignUtils.sign(signParameters.getSignAlg(), signKey, data).toUpperCase();
    }

    private Map<String, String> getParams(final SignParameters signParameters) {

        Map<String, String> params = Maps.newHashMap();
        params.put(Constants.TIMESTAMP, signParameters.getTimestamp());
        params.put(Constants.PATH, signParameters.getUri().getPath());
        params.put(Constants.VERSION, signParameters.getVersion());
        return params;
    }
}
